package org.javaweb.cms_web.controller;

import org.javaweb.cms_web.model.Article;
import org.javaweb.cms_web.model.ArticleDTO;
import org.javaweb.cms_web.model.Team;
import org.javaweb.cms_web.model.User;
import org.javaweb.cms_web.service.ArticleManagementService;
import org.javaweb.cms_web.service.TeamService;
import org.javaweb.cms_web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/articles")
public class ArticleController {

    @Autowired
    private ArticleManagementService articleManagementService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private UserService userService;

    // 显示文章列表页面
    @GetMapping("/list/{teamID}")
    public String showArticles(
            @PathVariable("teamID") int teamID,  // 从路径参数获取 teamID
            @RequestParam(value = "search", required = false) String search,  // 可选的搜索参数
            Model model) {

        List<ArticleDTO> articles;
        // 根据是否有搜索关键字来查询文章
        if (search != null && !search.isEmpty()) {
            articles = articleManagementService.getArticlesByTeamAndTitle(teamID, search);
        } else {
            articles = articleManagementService.getArticlesByTeam(teamID);
        }

        // 将查询结果和团队ID传递给视图
        model.addAttribute("articles", articles);
        model.addAttribute("teamID", teamID); // 传递团队ID
        return "article-list"; // 返回到展示文章列表的JSP页面
    }

    // 显示文章详情页面
    @GetMapping("/{articleID}/details")
    public String showArticleDetails(
            @PathVariable("articleID") int articleID,  // 从路径参数获取 articleID
            Model model) {

        // 获取文章详情
        ArticleDTO article = articleManagementService.getArticleById(articleID);
        if (article != null) {
            // 根据文章中的 teamId 和 userId 获取对应的团队和用户信息
            Team team = teamService.getTeamById(article.getTeamId());
            User user = userService.findUserById(article.getUserId());

            // 传递团队ID
            int teamID = team.getTeamId();
            model.addAttribute("teamID", teamID);

            // 假设 article 是你的文章对象
            String AttachmentLink = article.getAttachmentLink();
            String encodedAttachmentLink = articleManagementService.prepareUrl(article.getAttachmentLink());
            System.out.println("编码前:" + article.getAttachmentLink());
            article.setAttachmentLink(encodedAttachmentLink);
            System.out.println("编码后:" + encodedAttachmentLink);
            // 将文章、团队和用户信息传递到模型
            model.addAttribute("AttachmentLink", AttachmentLink);
            model.addAttribute("article", article);
            model.addAttribute("team", team);
            model.addAttribute("user", user);
        }
        return "article-details"; // 返回到文章详情的JSP页面
    }
}
